<?php


namespace console\spider\utils;


use console\spider\Params;

class HttpClient
{

    /**
     * http 请求
     * @return array['code':返回码,'context':文本]
     * @var string $url
     */
    public static function request($url)
    {

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($curl, CURLOPT_COOKIEFILE, Params::cookie_file);
        $content=curl_exec($curl);

        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if($code === 0){
            throw new Exception(curl_error($curl));
        }

        curl_close($curl);
        return array(
            'code' => $code,
            'content' => $content,
        );
    }

    /**
     * http 请求
     * @param $url
     * @param $params{'dir':目录，'name':文件名，'tag':调试信息]
     * @return void
     */
    public static function dataSave($url,$params)
    {
        if(!file_exists($params['dir'])){//检查文件夹是否存在
            mkdir ($params['dir']);    //没有就创建一个新文件夹
        }

        $pageNum = 0;

        do{
            $pageNum++;
            try {
                $data = HttpClient::request($url. $pageNum);
                $enrollmentPlanJson = json_decode($data['content']);
                $totalPages = $enrollmentPlanJson->pagingInfo->totalPages;

                if($totalPages > 0)
                {
                    echo PHP_EOL,$params['tag']."：totolPages: $totalPages pageNum: $pageNum \n";
                    $fp = fopen($params['dir'].$params['fileName']."$pageNum.json","w");
                    fwrite($fp,$data['content']);
                    fclose($fp);
                }
                else {
                    echo '.';
                }


            } catch (Exception $e) {
                echo $e;
                break;
            }
        }while($pageNum < $totalPages);
    }
}